package com.xykj.enterprise.wechat.wap.service.wxpush;

import com.xykj.enterprise.wechat.util.wechat.xml.AesException;
import com.xykj.enterprise.wechat.util.wechat.xml.WXBizMsgCrypt;
import com.xykj.enterprise.wechat.wap.service.BaseService;
import com.ydn.appserver.MinaAppClient;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Author zhouxu
 * @create 2021-02-23 17:47
 */
@Service
@Slf4j
public class SaasEventWxpushService extends BaseService {

    // 企业微信指定返回
    // 服务商在收到推送后都必须直接返回字符串 “success”，若返回值不是 “success”，企业微信会把返回内容当作错误信息
    public static final String RESPONSE_OK = "success";

    @Value("${wx.saas.Token}")
    private String sToken;
    @Value("${wx.saas.CorpID}")
    private String sCorpID;
    @Value("${wx.saas.EncodingAESKey}")
    private String sEncodingAESKey;
    @Value("${wx.saas.SuiteID}")
    private String SuiteID;
    @Value("${wx.saas.Secret}")
    private String Secret;

    @Autowired
    private MinaAppClient busiClient;

    public String verify(String sVerifyMsgSig, String sVerifyTimeStamp, String sVerifyNonce, String sVerifyEchoStr) throws AesException {
        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
        log.debug("sToken:{},sEncodingAESKey:{},sCorpID:{}", sToken, sEncodingAESKey, sCorpID);
        String sEchoStr = wxcpt.VerifyURL(
                sVerifyMsgSig,
                sVerifyTimeStamp,
                sVerifyNonce,
                sVerifyEchoStr
        );
        log.debug("sEchoStr:{}", sEchoStr);
        return sEchoStr;//需要返回的明文

    }

    public String post(String sVerifyMsgSig, String sVerifyTimeStamp, String sVerifyNonce, String data) throws AesException {
        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, SuiteID);
        log.debug("sToken:{},sEncodingAESKey:{},SuiteID:{}", sToken, sEncodingAESKey, SuiteID);
        String sMsg = wxcpt.DecryptMsg(
                sVerifyMsgSig,
                sVerifyTimeStamp,
                sVerifyNonce,
                data
        );
        log.debug("sMsg:{}", sMsg);

        // 业务处理
        Request request = new Request("SaasEventWxpush");
        request.setParameter("msgSignature", sVerifyMsgSig);
        request.setParameter("timestamp", sVerifyTimeStamp);
        request.setParameter("nonce", sVerifyNonce);
        request.setParameter("data", data);
        request.setParameter("msg", sMsg);

        request.setParameter("suite_id", SuiteID);
        request.setParameter("secret", Secret);

        Response response = busiClient.send(request);

        return RESPONSE_OK;

    }


}
